<template>
  <el-upload class="upload-demo" drag action="" :before-upload="beforeUpload" :file-list="fileList"
    :on-success="handleUploadSuccess" :on-error="handleUploadError">
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">点击或拖拽文件上传</div>
  </el-upload>
</template>

<script>
import axios from 'axios';
import { ref } from 'vue';

export default {
  setup() {
    const fileList = ref([]);

    // 分片大小
    const CHUNK_SIZE = 2 * 1024 * 1024; // 2MB

    const beforeUpload = (file) => {
      const fileSize = file.size;
      const chunkCount = Math.ceil(fileSize / CHUNK_SIZE);

      // 分片上传逻辑
      for (let i = 0; i < chunkCount; i++) {
        const start = i * CHUNK_SIZE;
        const end = Math.min(start + CHUNK_SIZE, fileSize);
        const chunk = file.slice(start, end);

        // 构造 FormData，包含文件片段和相关参数
        const formData = new FormData();
        formData.append('file', chunk);
        formData.append('filename', file.name);
        formData.append('fileIndex', i);
        formData.append('totalChunks', chunkCount);

        // 上传每个分片
        uploadChunk(formData, i);
      }

      // 阻止默认上传行为，因为我们是自定义上传
      return false;
    };

    const uploadChunk = async (formData, chunkIndex) => {
      try {
        const response = await axios.post('https://file.jitoushuizhan.cn/file/upload/chunkReady', { filename: 'a123.jpg' }, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        });

        if (response.data.success) {
          console.log(`分片 ${chunkIndex + 1} 上传成功`);
          // 在这里处理每个分片上传成功后的逻辑
          // 可以检查是否所有分片上传成功，如果是，则可以通知服务器合并分片
        } else {
          console.error(`分片 ${chunkIndex + 1} 上传失败`);
        }
      } catch (error) {
        console.error(`分片 ${chunkIndex + 1} 上传失败: `, error);
      }
    };

    const handleUploadSuccess = (response, file, fileList) => {
      console.log('文件上传成功', response);
    };

    const handleUploadError = (error, file, fileList) => {
      console.error('文件上传失败', error);
    };

    return {
      fileList,
      beforeUpload,
      handleUploadSuccess,
      handleUploadError,
    };
  },
};
</script>
